This demonstrates the mapping pattern.
Map is a mathematical term that means going from one value to a corresponding value.
This is also referred to as the transform pattern.
smaller_numbers.py
¶Write a function that creates a new list where each item has been divided by 2.
You can pass lists to functions and return lists from functions.
This demonstrates the filter pattern.
A new collection is created with certain items filtered out.
This demonstrates the selection pattern.
A single item is selected from a collection.
This demonstrates the accumulator pattern.
total
accumulates the values in the collection.
numbers = [1, 2, 3, 4, 5]
sum
¶sum(numbers)
15
sum(numbers) / len(numbers)
3.0
new_numbers = []
for number in numbers:
new_number = number + 7
new_numbers.append(new_number)
new_numbers
[8, 9, 10, 11, 12]
[number + 7 for number in numbers]
[8, 9, 10, 11, 12]
[number / 3 for number in numbers]
[0.3333333333333333, 0.6666666666666666, 1.0, 1.3333333333333333, 1.6666666666666667]
[number ** 2 for number in numbers]
[1, 4, 9, 16, 25]
[number ** 0.5 for number in numbers]
[1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979]
new_numbers = []
for number in numbers:
if number > 3:
new_numbers.append(number)
new_numbers
[4, 5]
[number for number in numbers if number > 3]
[4, 5]
[number for number in numbers if number % 2 == 0]
[2, 4]
[number for number in numbers if number * 5 < 20]
[1, 2, 3]
nums = [0, 7, 2, 14, 20, 32, 5, 12]
# subtract 7
nums = [number - 7 for number in nums]
# Keep 0 <= num <= 10
def is_keeper(number):
return 0 <= number <= 10
nums = [number for number in nums if is_keeper(number)]
print(nums)
[0, 7, 5]